package com.qdu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

	//注入要使用的UserDetailsService对象，这里注入的是自定义的CustomUserDetailsService的对象
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//指定验证和授权用户使用的UserDetailsService对象是哪个
		//并且指定使用的密码加密器
		auth.userDetailsService(userDetailsService)
		    .passwordEncoder(passwordEncoder()); 
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/css/**","/js/**","/img/**");
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
		        .antMatchers("/","/index","/login","/login_failed").permitAll()
		        .antMatchers("/stu/**").hasAnyRole("student")
		        .antMatchers("/teach/**").hasAnyRole("teacher")
		        .antMatchers("/mc/**").hasAnyRole("admin")
		        .anyRequest().authenticated()
		    .and()
		    .formLogin().loginPage("/login")
		                .defaultSuccessUrl("/",true)
		                .failureUrl("/login_failed")
		    .and()		   
	    		.rememberMe()
	    		.rememberMeCookieName("remember")
	    		.rememberMeParameter("rememberMe")
	    		.tokenValiditySeconds(7*24*60*60)
	    	.and()
		    .headers().frameOptions().sameOrigin()
		    .and()
		    .csrf().disable();
	}
	
	@Bean
	public BCryptPasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	} 
}
